package edu.gdpi.dao.impl;

import edu.gdpi.dao.GoodsDao;
import edu.gdpi.entity.Goods;
import edu.gdpi.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class GoodsDaoImpl implements GoodsDao {
    @Override
    public Goods selectGoodsById(int id) {
        Goods goods = null;
        try {
            Connection conn = DBUtil.getConnection();
            String sql = "select * from goods where id = ?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setInt(1, id);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                goods = new Goods();
                goods.setId(rs.getInt("id"));
                goods.setName(rs.getString("name"));
                goods.setPrice(rs.getDouble("price"));
                goods.setDescription(rs.getString("description"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return goods;
    }

    @Override
    public List<Goods> listGoods() {
        List<Goods> goodsList = null;
        try {
            Connection conn = DBUtil.getConnection();
            String sql = "select * from goods";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            goodsList = new ArrayList<>();
            while (rs.next()) {
                Goods goods = new Goods();
                goods.setId(rs.getInt("id"));
                goods.setName(rs.getString("name"));
                goods.setPrice(rs.getDouble("price"));
                goods.setDescription(rs.getString("description"));
                goodsList.add(goods);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return goodsList;
    }
}
